package com.wangxiaonan.berry.controller;

import com.wangxiaonan.berry.entity.Barn;
import com.wangxiaonan.berry.exception.ServiceException;
import com.wangxiaonan.berry.handler.ResponseWrapper;
import com.wangxiaonan.berry.service.BarnService;
import com.wangxiaonan.berry.util.PoiUtils;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: wangxiaonan
 * @Date: 2019/7/1
 **/
@CrossOrigin
@RestController
@RequestMapping("barn")
public class BarnController {

    private static final Logger logger = LoggerFactory.getLogger(BarnController.class);

    @Resource
    private BarnService barnService;

    @RequestMapping(value = "/{id}")
    public ResponseWrapper findById(@PathVariable int id) {
        Barn barn = barnService.findById(id);
        return new ResponseWrapper().success(barn);
    }

    @RequestMapping(value = "/cargo", method = RequestMethod.POST)
    public ResponseWrapper store(@RequestBody Barn barn, HttpServletRequest request) {
        if (StringUtils.isEmpty(barn.getType())) {
            barn.setType(request.getHeader("User-Agent"));
        }
        try {
            barnService.storeBarn(barn);
        } catch (Exception e) {
            logger.error("存储异常", e);
            throw new ServiceException("存储数据失败！");
        }

        return new ResponseWrapper().success();
    }

    @RequestMapping(value = "/excel", method = RequestMethod.GET)
    public void export(@RequestParam(required = false) String type,
            @PageableDefault(size = 1000, sort = "id", direction = Direction.DESC) Pageable pageable,
            HttpServletRequest request, HttpServletResponse response) {
        List<String> titles = barnService.summariseTitles(type);
        if (CollectionUtils.isEmpty(titles)) {
            logger.info("导出数据为空 type：{}", type);
            return;
        }

        HSSFWorkbook workbook = new HSSFWorkbook();
        Map<String, String[][]> sheets = new HashMap<>();

        // 内容，从第二行开始，第一行留给标题
        String[][] sheetContent = barnService.collectCellValue(titles, 1, type, pageable);

        // 标题
        for (int i = 0; i < titles.size(); ++i) {
            sheetContent[0][i] = titles.get(i);
        }

        sheets.put("sheet", sheetContent);
        PoiUtils.createWorkbook(sheets, workbook);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String typeStr = "";
        if (!StringUtils.isEmpty(type)) {
            typeStr = type + "-";
        }
        String fileName = "设备指纹数据-" + typeStr + sdf.format(new Date()) + ".xls";
        try {
            fileName = new String(fileName.getBytes(), "ISO8859-1");
        } catch (UnsupportedEncodingException e) {
            logger.error("文件名称转换错误", e);
        }
        response.setContentType("application/octet-stream;charset=ISO8859-1");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + fileName);
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        try (OutputStream os = response.getOutputStream()) {
            workbook.write(os);
            os.flush();
        } catch (IOException e) {
            logger.error("导出失败", e);
        }

    }
}
